<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="订单号" prop="orderCode">
        <el-input
          v-model="queryParams.orderCode"
          placeholder="请输入订单号"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="用户ID" prop="userId">
        <el-input
          v-model="queryParams.userId"
          placeholder="请输入用户ID"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="下单时间" prop="orderTime">
        <el-date-picker clearable
                        v-model="queryParams.orderTime"
                        type="datetime"
                        value-format="yyyy-MM-dd"
                        placeholder="请选择下单时间"
        >
        </el-date-picker>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['admin:order:export']"
        >导出
        </el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="orderList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center"/>
      <!--      <el-table-column label="订单ID" align="center" prop="id" />-->
      <el-table-column label="订单号" align="center" prop="orderCode"/>
      <el-table-column label="总金额" align="center" prop="totalMoney"/>
      <el-table-column label="下单时间" align="center" prop="orderTime" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.orderTime, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="订单状态" align="center" prop="orderStatus">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.sys_order_msg" :value="scope.row.orderStatus"/>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <!-- 查看详情触发对话框的按钮,并且自动获取userId -->
        <template slot-scope="scope">
          <el-button type="primary" size="mini" @click="selectByUserId(scope.row.userId)">查看订单详情</el-button>
        </template>
      </el-table-column>
    </el-table>
    <!-- 订单详情对话框 -->
    <el-dialog
      title="订单详情"
      :visible.sync="dialogVisible"
      width="60%"
    >
      <!-- 订单确认页面内容 -->
      <div class="order-container">
        <!-- 顶部标题 -->
        <div class="page-header">
          <!--          <div class="back-btn" @click="goBack">-->
          <!--            <i class="el-icon-arrow-left"></i>-->
          <!--          </div>-->
          <h2>订单详情</h2>
        </div>

        <!-- 收货地址 -->
        <div class="addressArea">
          收货地址
          <li v-for="(item, key) in orderAndUserList" :key="key">
            <p>收货人: {{ item.name }}</p>
            <p>手机号: {{ item.phone }}</p>
            <p>所在地区: {{ item.address }}</p>
            <p>详细地址: {{ item.addressDetail }}</p>
            <p>是否默认: {{ item.isDefault == '0' ? '是' : '否' }}</p>
            <p>
              是否使用:
              <el-radio v-model="defaultAddress" :label="item.id">使用当前</el-radio>
            </p>
          </li>
        </div>

        <!-- 商品信息 -->
        <div class="section goods-section">
          <div class="section-title">
            <i class="el-icon-shopping-bag-1"></i>
            <span>商品信息</span>
          </div>
          <div class="goods-list">
            <div
              class="goods-item"
              v-for="order in orderAndGoodsList"
              :key="order.id"
            >
              <div v-for="goods in order.mlGoodsDtoList" :key="goods.id">
                <el-image
                  :src="goods.coverImage"
                  class="goods-img"
                  :alt="goods.goodsName"
                  fit="cover"
                  :preview-src-list="goods.detailImage.split(',')"
                >
                  <div slot="error" class="image-slot">
                    <i class="el-icon-picture-outline"></i>
                  </div>
                </el-image>
                <div class="goods-info">
                  <h4 class="goods-name">{{ goods.goodsName }}</h4>
                  <p class="goods-spec">{{ goods.goodsFeature }}</p>
                  <div class="goods-price-wrap">
                    <span class="price">¥{{ formatPrice(goods.salePrice) }}</span>
                    <span class="count">x1</span>
                  </div>
                </div>
              </div>
            </div>
          </div>

          <!-- 配送方式 -->
          <div class="section delivery-section">
            <div class="section-title">
              <i class="el-icon-truck"></i>
              <span>配送方式</span>
            </div>

            <div class="delivery-options">
              <div
                class="delivery-item"
                v-for="item in deliveryOptions"
                :key="item.id"
                :class="{ active: selectedDelivery === item.id }"
                @click="selectDelivery(item)"
              >
                <div class="delivery-info">
                  <span class="delivery-name">{{ item.name }}</span>
                  <span class="delivery-time">{{ item.time }}</span>
                </div>
                <span class="delivery-fee" :class="{ free: item.fee === 0 }">
        {{ item.fee > 0 ? `¥${formatPrice(item.fee)}` : '免费' }}
      </span>
              </div>
            </div>
          </div>
          <!-- 订单金额 -->
          <div class="section price-section">
            <div class="price-item">
              <span>商品总额</span>
              <span>¥{{ formatPrice(totalMoney) }}</span>
            </div>
            <div class="price-item">
              <span>优惠券</span>
              <span>¥0.00</span>
            </div>
            <div class="price-item">
              <span>邮费</span>
              <span>¥{{ formatPrice(shippingFee) }}</span>
            </div>
            <div class="price-item">
              <span>配送费</span>
              <span>¥{{ formatPrice(deliveryFee) }}</span>
            </div>
            <div class="price-item total">
              <span>实付款</span>
              <span class="final-price">¥{{ formatPrice(actualPayMoney) }}</span>
            </div>
          </div>
        </div>

        <!-- 合计部分 -->
        <div class="submit-section">
          <div class="price-info">
            <span>合计：</span>
            <span class="final-price">¥{{ formatPrice(actualPayMoney) }}</span>
          </div>
        </div>
      </div>
      <!-- 对话框底部按钮 -->
      <span slot="footer" class="dialog-footer">
        <el-button @click="getList()">取 消</el-button>
        <el-button type="primary" @click="getList()">确 定</el-button>
      </span>
    </el-dialog>
    <!-- 分页 -->
    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />
  </div>
</template>

<script>
import { listOrder, getOrder, delOrder, addOrder, updateOrder } from '@/api/admin/order'
import { sendRequest } from '@/utils/request'

export default {
  name: 'Order',
  dicts: ['sys_order_msg'],
  data() {
    return {
      shippingFee: 0,      // 邮费
      deliveryFee: 0,      // 配送费
      actualPayMoney: 0,   // 实付款（商品金额+邮费+配送费）
      dialogVisible: false, // 控制对话框显示
      defaultAddress: '',
      //默认选择标准配送方式
      selectedDelivery: 1,
      submitting: false,
      //单个商品表信息
      mlGoodsDtoList: {},
      //订单表和商品表联表信息
      orderAndGoodsList: [],
      //用户表信息
      sysUserDto: {},
      //订单总金额
      totalMoney: 0,
      // 订单对象
      order: {},
      // 配送选项
      deliveryOptions: [
        { id: 1, name: '标准配送', time: '3-5天送达', fee: 0 },
        { id: 2, name: '加急配送', time: '1-2天送达', fee: 10 }
      ],
      // 用户地址列表
      orderAndUserList: [],
      // 遮罩层
      loading: true,
      // // 选中数组
      // ids: [],
      // // 非单个禁用
      // single: true,
      // // 非多个禁用
      // multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 订单表格数据
      orderList: [],
      // 弹出层标题
      title: '',
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        orderCode: null,
        userId: null,
        orderTime: null
      },
      // 表单参数
      form: {}
      // // 表单校验
      // rules: {
      // }
    }
  },
  created() {
    this.getList()
    // this.getOrderInfo();
  },
  methods: {
    // 添加格式化价格的方法
    formatPrice(price) {
      if (!price) return '0.00'
      return parseFloat(price).toFixed(2)
    },

    // 选择配送方式
    selectDelivery(item) {
      this.selectedDelivery = item.id
      // 更新配送费
      this.deliveryFee = item.fee
      // 重新计算实付款
      this.calculateTotalAmount()
    },
    // 计算总金额
    calculateTotalAmount() {
      // 计算实付款（商品金额 + 邮费 + 配送费）
      this.actualPayMoney = this.totalMoney + this.shippingFee + this.deliveryFee
    },
    // 根据用户ID查询订单详情
    selectByUserId(userId) {
      this.dialogVisible = true
      this.loading = true
      sendRequest('post', '/admin/order/selectUsernameAndAddressByUserId/' + userId).then(res => {
        if (res.code === 200) {
          // 绑定用户信息
          this.sysUserDto = res.UsernameAndAddressByUserId.sysUserDto;
          // 绑定订单和商品信息
          this.orderAndGoodsList = res.selectGoodsInfoWhereUserId.orderAndGoodsList;
          // 构建地址列表
          this.orderAndUserList = [{
            id: this.sysUserDto.userId,
            name: this.sysUserDto.nickName,
            phone: this.sysUserDto.phonenumber,
            address: this.sysUserDto.address || "未设置",
            addressDetail: this.sysUserDto.address || "未设置详细地址",
            isDefault: "0"
          }];
          // 设置默认地址
          this.defaultAddress = this.sysUserDto.userId;
          // 如果有订单, 设置订单信息
          if (this.orderAndGoodsList && this.orderAndGoodsList.length > 0) {
            // 设置第一个订单为当前订单
            this.order = this.orderAndGoodsList[0]
            // 计算所有订单的商品金额和邮费
            this.totalMoney = 0
            this.shippingFee = 0
            for (let i = 0; i < this.orderAndGoodsList.length; i++) {
              // 累加商品金额
              this.totalMoney += parseFloat(this.orderAndGoodsList[i].totalMoney || 0)

              // 累加邮费（如果商品列表中有邮费信息）
              if (this.orderAndGoodsList[i].mlGoodsDtoList && this.orderAndGoodsList[i].mlGoodsDtoList.length > 0) {
                for (let j = 0; j < this.orderAndGoodsList[i].mlGoodsDtoList.length; j++) {
                  this.shippingFee += parseFloat(this.orderAndGoodsList[i].mlGoodsDtoList[j].shippingMoney || 0)
                }
              }
            }

            // 设置默认配送方式
            this.selectedDelivery = 1
            this.deliveryFee = this.deliveryOptions[0].fee

            // 计算实付款
            this.calculateTotalAmount()
          }
        } else {
          this.$message.error('获取订单详情失败')
        }
        this.loading = false
      }).catch(error => {
        console.error('获取订单详情出错:', error)
        this.$message.error('获取订单详情出错')
        this.loading = false
      })
    },
    /** 查询订单列表 */
    getList() {
      this.dialogVisible = false
      this.loading = true
      listOrder(this.queryParams).then(response => {
        this.orderList = response.rows
        this.total = response.total
        this.loading = false
      })
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        orderCode: null,
        userId: null,
        totalMoney: null,
        orderTime: null,
        orderStatus: null,
        goodsId: null
      }
      this.resetForm('form')
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1
      this.getList()
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm('queryForm')
      this.handleQuery()
    }
  }
}
</script>
<style scoped>
.order-wrapper {
  min-height: 100vh;
  background: #f7f8fa;
  padding: 20px;
  box-sizing: border-box;
}

.order-container {
  max-width: 800px;
  margin: 0 auto;
  background: #fff;
  border-radius: 16px;
  box-shadow: 0 4px 16px rgba(0, 0, 0, 0.06);
  overflow: hidden;
}

.page-header {
  display: flex;
  align-items: center;
  padding: 20px;
  border-bottom: 1px solid #f0f0f0;
  background: #fff;
}

.back-btn {
  font-size: 20px;
  color: #333;
  cursor: pointer;
  margin-right: 15px;
  transition: all 0.3s;
}

.back-btn:hover {
  color: #ff6700;
  transform: translateX(-3px);
}

.page-header h2 {
  margin: 0;
  font-size: 18px;
  font-weight: 600;
  color: #333;
}

.section {
  padding: 24px;
  border-bottom: 1px solid #f0f0f0;
  transition: all 0.3s;
}

.section:hover {
  background: #fafafa;
}

.section-title {
  display: flex;
  align-items: center;
  margin-bottom: 24px;
  font-size: 16px;
  font-weight: 600;
  color: #333;
}

.section-title i {
  margin-right: 10px;
  color: #ff6700;
  font-size: 20px;
}

.address-form {
  max-width: 100%;
}

.goods-list {
  margin-top: 15px;
}

.goods-item {
  display: flex;
  padding: 20px;
  background: #fafafa;
  border-radius: 12px;
  margin-bottom: 15px;
  transition: all 0.3s;
}

.goods-item:hover {
  transform: translateY(-2px);
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.05);
}

.goods-item:last-child {
  margin-bottom: 0;
}

.goods-img {
  width: 100px;
  height: 100px;
  border-radius: 8px;
  margin-right: 20px;
  overflow: hidden;
}

.image-slot {
  display: flex;
  justify-content: center;
  align-items: center;
  width: 100%;
  height: 100%;
  background: #f5f5f5;
  color: #909399;
  font-size: 30px;
}

.goods-info {
  flex: 1;
  display: flex;
  flex-direction: column;
  justify-content: space-between;
}

.goods-name {
  margin: 0 0 8px;
  font-size: 16px;
  font-weight: 500;
  color: #333;
  line-height: 1.4;
}

.goods-spec {
  color: #999;
  font-size: 14px;
  margin: 0 0 8px;
}

.goods-price-wrap {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.price {
  color: #ff6700;
  font-size: 18px;
  font-weight: 600;
}

.count {
  color: #999;
  font-size: 14px;
}

.delivery-options {
  margin-top: 15px;
}

.delivery-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 20px;
  background: #fafafa;
  border-radius: 12px;
  margin-bottom: 12px;
  cursor: pointer;
  transition: all 0.3s;
}

.delivery-item:hover {
  transform: translateY(-2px);
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.05);
}

.delivery-item.active {
  background: #ff6700;
  color: #fff;
}

.delivery-item.active .delivery-time,
.delivery-item.active .delivery-fee {
  color: rgba(255, 255, 255, 0.8);
}

.delivery-name {
  font-size: 16px;
  font-weight: 500;
  margin-bottom: 6px;
}

.delivery-time {
  font-size: 14px;
  color: #999;
}

.delivery-fee {
  font-weight: 500;
}

.delivery-fee.free {
  color: #52c41a;
}

.price-item {
  display: flex;
  justify-content: space-between;
  margin-bottom: 12px;
  font-size: 14px;
  color: #666;
}

.total {
  margin-top: 20px;
  padding-top: 20px;
  border-top: 1px solid #f0f0f0;
  font-size: 16px;
  color: #333;
}

.final-price {
  color: #ff6700;
  font-size: 24px;
  font-weight: 600;
}

.submit-section {
  position: sticky;
  bottom: 0;
  background: #fff;
  padding: 20px;
  display: flex;
  justify-content: space-between;
  align-items: center;
  box-shadow: 0 -4px 16px rgba(0, 0, 0, 0.06);
}

.submit-btn {
  padding: 12px 36px;
  font-size: 16px;
  border-radius: 24px;
  transition: all 0.3s;
}

.submit-btn:not(:disabled):hover {
  transform: translateY(-2px);
  box-shadow: 0 4px 12px rgba(255, 103, 0, 0.3);
}

/* Element UI 样式覆盖 */

.default-address-text {
  color: #666;
  font-size: 14px;
}

/* 响应式设计 */
@media screen and (max-width: 768px) {
  .order-wrapper {
    padding: 10px;
  }

  .goods-img {
    width: 80px;
    height: 80px;
  }

  .submit-btn {
    padding: 10px 24px;
  }

  .section {
    padding: 16px;
  }

  .goods-item {
    padding: 15px;
  }

  .delivery-item {
    padding: 15px;
  }
}

.addressArea {
  overflow: hidden;
}

.addressArea li {
  list-style: none;
  float: left;
  width: 33.33%;
  border: 1px solid red;
  padding: 20px;
  margin-right: 10px;
}

.el-radio__original {
  inert: true;
}
</style>
